package payment.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.*;
import com.example.utils.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import payment.mapper.ShippingOrderMapper;
import payment.mapper.TruckOrderMapper;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class PaymentService {

    private static final String SOURCE = "payment";
    private static final Logger LOG = LoggerFactory.getLogger(PaymentService.class);
    @Resource
    TruckOrderMapper truckOrderMapper;
    @Resource
    ShippingOrderMapper shippingOrderMapper;
    @Resource
    KafkaTemplate<Long, Message> template;

    public void settle(Message m) {
        Long orderId = m.getOrderId();
        ShippingOrder s = shippingOrderMapper.selectById(orderId);
        List<TruckOrder> tl = truckOrderMapper.selectList(new QueryWrapper<TruckOrder>().eq("order_id",s.getId()));
        double unexpectedCost = 0;
        for(TruckOrder t:tl){
            unexpectedCost+=t.getUnexpectedCost();
        }
        if(unexpectedCost>=0){
            s.setUnexpectedCost(unexpectedCost);
            s.setTotalPrice(s.getLogisticsCost()+unexpectedCost);
            shippingOrderMapper.updateById(s);
            m.setStatus("ACCEPT");
        }else m.setStatus("REJECT");
        m.setSource(SOURCE);
        template.send("payment-orders", m.getOrderId(), m);
        LOG.info("Sent: {}", m);
    }

    public void rollback(Message m) {
        ShippingOrder s = shippingOrderMapper.selectById(m.getOrderId());
        if (m.getStatus().equals("ROLLBACK") && !m.getSource().equals(SOURCE)) {
            s.setUnexpectedCost(0D);
            s.setTotalPrice(s.getLogisticsCost()+ s.getUnexpectedCost());
            shippingOrderMapper.updateById(s);
        }
    }
}
